BUILDING.GUIs = {}
BUILDING.LastClose = 0

function BUILDING:GetMousePos()
	
	local Item = self.List[ self:Get() ]
	
	if IsValid( Item.VGUI ) then
		
		return ScrW() * 0.5 + math.cos( Item.VGUI.MoveAngle ) * 30,
			ScrH() * 0.5 + math.sin( Item.VGUI.MoveAngle ) * 30
			
	end
	
	return 0,0
	
end

function BUILDING:OpenPanels()

	for k, v in pairs( self.List ) do
		if !v.VGUI then
			v.VGUI = vgui.Create( "BuildItem" )
			v.VGUI:SetId( k )
		end
		
		v.VGUI:Open()
	end
	
	self:UpdateAngles()
	
	local x,y = self:GetMousePos()
	
	gui.EnableScreenClicker(true)
	gui.SetMousePos( x,y )
	hook.Add("Think", "UpdateMouseCommander", function()
		BUILDING:UpdateMouseActive()
	end )
	
	if self.DEBUG then
		Msg( CurTime() .. " - Setting mouse to: " .. x .. " - " .. y .. "\n")
	end

end


function BUILDING:ClosePanels()
	
	if self.LastClose == CurTime() then //Closing function seems to be being called twice and messing everything up
		return
	end
	
	self.LastClose = CurTime()
	
	for _, v in pairs( self.List ) do
		if v.VGUI then
			v.VGUI:Close()
		end
	end
	
	if self.DEBUG then
		Msg( CurTime() .. " Closing!\n" )
	end

	self:Set( self:ActiveItem() )
	
	gui.EnableScreenClicker(false)
	hook.Remove("Think", "UpdateMouseCommander")
	
	hook.Call("BuildChoose", GAMEMODE )

end

function BUILDING:ActiveItem()

	local MouseX, MouseY = gui.MousePos()
	
	local MouseAng = math.Rad2Deg( math.atan2(
		MouseY - ScrH() * 0.5,
		MouseX - ScrW() * 0.5
	) )
	
	local TotalCount = table.Count( self.List )
	local AngleForEach = 360 / TotalCount
	
	if MouseAng < 0 then
		MouseAng = MouseAng + 360
	end
	
	return math.floor( MouseAng / AngleForEach ) + 1

end

function BUILDING:UpdateMouseActive()
	
	local GoItem = self:ActiveItem()
	
	for k, v in pairs( self.List ) do
		if v.VGUI then
			v.VGUI:SetActive( k == GoItem )
		end
	end
	
end

function BUILDING:UpdateAngles()

	local TotalCount = table.Count( self.List )
	local ExtraSpace = 360 / TotalCount * 0.5
	
	for k, v in pairs( self.List ) do
		if v.VGUI then
			v.VGUI:SetAngle( ExtraSpace + 360 / TotalCount * (k-1) )
		end
	end

end